﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Common;
using DevExpress.XtraEditors;
using Model;
using System.Linq;

namespace TaxiDispatchClient
{
    public partial class TaxiCotrolForm : XtraForm
    {
        private readonly string _taxiId;
        private readonly string _driverPhone;
        private readonly Socket _socket;
        private readonly Dictionary<int, byte[]> _imageDataBuffer = new Dictionary<int, byte[]>();
        private readonly Dictionary<int, byte[]> _videoDataBuffer = new Dictionary<int, byte[]>();

        private readonly string _imageFloderPath = Application.StartupPath + @"\TaxiImages\" + DateTime.Now.ToString("yyyy-MM-dd") + @"\";
        private readonly string _videoFloderPath = Application.StartupPath + @"\Record\" + DateTime.Now.ToString("yyyy-MM-dd") + @"\";

        private readonly Thread _tReceThread;
        readonly string _transferServerIp = OperateConfig.GetClientTransferServerIp();

        public TaxiCotrolForm()
        {
            InitializeComponent();
        }

        public TaxiCotrolForm(DataRow dr)
        {
            InitializeComponent();


            for (int i = 1; i < 100; i++)
            {
                if (i < 10)
                {
                    comboBoxEdit_AdId.Properties.Items.Add("0" + i);
                }
                else
                {
                    comboBoxEdit_AdId.Properties.Items.Add(i);
                }
            }
            comboBoxEdit_AdId.SelectedIndex = 0;
            try
            {
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipAddress = IPAddress.Parse(_transferServerIp);
                IPEndPoint address = new IPEndPoint(ipAddress, ConstParameters.TransferListenPort);
                _socket.Connect(address);
                _socket.NoDelay = true;
                _tReceThread = new Thread(ReceData);
                _tReceThread.Start();
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                XtraMessageBox.Show("与中转服务器通讯失败，请检查中转服务器IP设置是否正常");
            }

            //gridcontrol
            try
            {
                // _dtTaxiList
                labelControl_DriverName.Text = dr["司机姓名"].ToString();
                labelControl_TaxiNo.Text = dr["出租车牌照"].ToString();
                labelControl_DriverPhone.Text = dr["司机号码"].ToString();
                labelControl_TaxiState.Text = dr["出租车状态"].ToString();
                labelControl_TaxiType.Text = dr["出租车车型"].ToString();
                labelControl_corp.Text = dr["所属公司"].ToString();
                labelControl_UpdateTime.Text = dr["数据更新时间"].ToString();
                labelControl_TaxiIp.Text = dr["IP地址"].ToString();
                _driverPhone = labelControl_DriverPhone.Text;
                _taxiId = dr["出租车ID"].ToString();

                var dt = MainForm.PositionService.TaxiAdGetList("taxiid=" + _taxiId).Tables[0];
                gridControl1.DataSource = dt;
                gridView1.Columns["id"].Visible = false;
                gridView1.Columns["taxiId"].Visible = false;
                gridView1.Columns["ADId"].Caption = "序号";
                gridView1.Columns["ADId"].Width = 40;
                gridView1.Columns["ADId"].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gridView1.Columns["ADId"].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;



                gridView1.Columns["ADContent"].Caption = "广告内容";
                //gridView1.Columns["ADContent"].Width = 100;
                //gridView1.Columns["ADId"].Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
                //gridView1.Columns["ADContent"].Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;


                gridView1.Columns["ADRollspeed"].Caption = "滚动速度";
                gridView1.Columns["ADRollspeed"].Width = 60;
                gridView1.Columns["ADRollspeed"].Visible = true;

                gridView1.Columns["ADEffect"].Caption = "滚动特效";
                gridView1.Columns["ADEffect"].Width = 60;

                gridView1.Columns["ADStaytime"].Caption = "停留时间";
                gridView1.Columns["ADStaytime"].Width = 60;

                gridView1.Columns["STime1"].Visible = false;
                gridView1.Columns["STime2"].Visible = false;
                gridView1.Columns["STime3"].Visible = false;
                gridView1.Columns["STime4"].Visible = false;

                gridView1.Columns["ETime1"].Visible = false;
                gridView1.Columns["ETime2"].Visible = false;
                gridView1.Columns["ETime3"].Visible = false;
                gridView1.Columns["ETime4"].Visible = false;


            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex, true);
            }
        }

        private void simpleButton_add_Click(object sender, EventArgs e)
        {
            if (simpleButton_add.Text == "添加")
            {
                comboBoxEdit_AdId.Enabled = true;
                memoEdit_AdContent.Enabled = true;
                comboBoxEdit_AdEffects.Enabled = true;
                comboBoxEdit_RollSpeed.Enabled = true;
                comboBoxEdit_stayTime.Enabled = true;
                memoEdit_AdContent.Text = "";
                simpleButton_add.Text = "保存";
                gridControl1.Enabled = false;

                simpleButton_modify.Visible = false;
                simpleButton_delete.Visible = false;
                simpleButton_cancel.Visible = true;
                simpleButton_cancel.Location = new Point(764, 351);
            }
            else
            {
                try
                {
                    if (!CheckInput())
                    {
                        return;
                    }
                    string strCommand = GetSetTaxiAdStrCmd();
                    byte[] messageBody = Encoding.GetEncoding("GBK").GetBytes(strCommand);
                    if (SendData(ConstParameters.CmdSetTaxiAd, messageBody))
                    {
                        string strTaxiId = _taxiId;
                        string strAdId = comboBoxEdit_AdId.SelectedItem.ToString();

                        //判断该编号广告是否已存在，若有，则更新，没有则添加
                        if (MainForm.PositionService.TaxiAdExist(int.Parse(strTaxiId), int.Parse(strAdId)))
                        {
                            UpdateAD();
                        }
                        else
                        {
                            AddAD();
                        }

                        gridControl1.Enabled = true;
                        simpleButton_modify.Visible = true;
                        simpleButton_delete.Visible = true;
                        simpleButton_cancel.Visible = false;
                        simpleButton_add.Text = "添加";
                        comboBoxEdit_AdId.Enabled = false;
                        memoEdit_AdContent.Enabled = false;
                        memoEdit_AdContent.Text = "";
                        comboBoxEdit_AdEffects.Enabled = false;
                        comboBoxEdit_RollSpeed.Enabled = false;
                        comboBoxEdit_stayTime.Enabled = false;
                    }
                    else
                    {
                        XtraMessageBox.Show("通讯失败，设置不成功");
                    }


                }
                catch (Exception ex)
                {
                    CommonRoutine.HandlingExceptions(ex);
                }
            }
        }

        private void simpleButton_cancel_Click(object sender, EventArgs e)
        {
            gridControl1.Enabled = true;
            simpleButton_add.Visible = true;
            simpleButton_modify.Visible = true;
            simpleButton_delete.Visible = true;
            simpleButton_cancel.Visible = false;

            simpleButton_add.Text = "添加";
            simpleButton_modify.Text = "修改";
            simpleButton_modify.Location = new Point(764, 351);
            comboBoxEdit_AdId.Enabled = false;
            memoEdit_AdContent.Enabled = false;
            comboBoxEdit_AdEffects.Enabled = false;
            comboBoxEdit_RollSpeed.Enabled = false;
            comboBoxEdit_stayTime.Enabled = false;
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if (row != null)
            {
                int adid = int.Parse(row["ADID"].ToString());
                if (adid < 10)
                {
                    comboBoxEdit_AdId.Text = "0" + adid;
                }
                else
                {
                    comboBoxEdit_AdId.Text = adid.ToString(CultureInfo.InvariantCulture);
                }

                memoEdit_AdContent.Text = row["ADContent"].ToString();

                comboBoxEdit_RollSpeed.SelectedIndex = int.Parse(row["ADRollspeed"].ToString());
                comboBoxEdit_AdEffects.SelectedIndex = int.Parse(row["ADEffect"].ToString());
                comboBoxEdit_stayTime.SelectedIndex = int.Parse(row["ADStaytime"].ToString());

                simpleButton_modify.Enabled = true;
            }
        }

        private void simpleButton_delete_Click(object sender, EventArgs e)
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if (row != null)
            {
                int id = int.Parse(row["id"].ToString());
                try
                {
                    if (XtraMessageBox.Show("确认删除该记录？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //string idtemp = id < 10 ? "0" + id : id.ToString(CultureInfo.InvariantCulture);
                        //string strDeleteCmd = GetDeleteTaxiAdStrCmd(idtemp);
                        //byte[] messageBody = Encoding.GetEncoding("GBK").GetBytes(strDeleteCmd);
                        //if (SendData(ConstParameters.CmdSetTaxiAd, messageBody))
                        // {
                        if (MainForm.PositionService.TaxiAdDelete(id))
                        {
                            XtraMessageBox.Show("删除成功");
                            memoEdit_AdContent.Text = "";
                        }
                        else
                        {
                            XtraMessageBox.Show("删除失败");
                        }
                        gridControl1.DataSource = MainForm.PositionService.TaxiAdGetList("taxiid=" +
                            _taxiId).Tables[0];
                        //}
                        //else
                        //{
                        //    XtraMessageBox.Show("通讯失败，设置不成功");
                        //}


                    }
                }
                catch (Exception ex)
                {
                    CommonRoutine.HandlingExceptions(ex);
                }
            }
        }

        private void simpleButton_modify_Click(object sender, EventArgs e)
        {
            if (simpleButton_modify.Text == "修改")
            {
                simpleButton_add.Visible = false;
                simpleButton_modify.Location = new Point(649, 351);
                simpleButton_modify.Text = "保存";
                simpleButton_delete.Visible = false;
                simpleButton_cancel.Visible = true;
                simpleButton_cancel.Location = new Point(764, 351);
                gridControl1.Enabled = false;
                memoEdit_AdContent.Enabled = true;

                comboBoxEdit_AdEffects.Enabled = true;
                comboBoxEdit_RollSpeed.Enabled = true;
                comboBoxEdit_stayTime.Enabled = true;
            }
            else
            {
                try
                {

                    if (!CheckInput())
                    {
                        return;
                    }

                    string strTaxiId = _taxiId;
                    string strAdId = comboBoxEdit_AdId.SelectedItem.ToString();


                    string strCommand = GetSetTaxiAdStrCmd();
                    byte[] messageBody = Encoding.GetEncoding("GBK").GetBytes(strCommand);
                    if (SendData(ConstParameters.CmdSetTaxiAd, messageBody))
                    {
                        //判断该编号广告是否已存在，若有，则更新，没有则添加
                        if (MainForm.PositionService.TaxiAdExist(int.Parse(strTaxiId), int.Parse(strAdId)))
                        {
                            UpdateAD();
                        }
                        else
                        {
                            AddAD();
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("通讯失败，设置不成功");
                    }


                }
                catch (Exception ex)
                {
                    CommonRoutine.HandlingExceptions(ex);
                    return;
                }
                gridControl1.Enabled = true;
                simpleButton_add.Visible = true;
                simpleButton_modify.Visible = true;
                simpleButton_delete.Visible = true;
                simpleButton_cancel.Visible = false;
                simpleButton_modify.Text = "修改";
                simpleButton_modify.Location = new Point(764, 351);
                memoEdit_AdContent.Enabled = false;
                comboBoxEdit_AdId.Enabled = false;
                comboBoxEdit_AdEffects.Enabled = false;
                comboBoxEdit_RollSpeed.Enabled = false;
                comboBoxEdit_stayTime.Enabled = false;

            }
        }

        private string GetSetTaxiAdStrCmd()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("FF");  // LED Address  (2L)
            sb.Append(comboBoxEdit_AdId.Text); //AD serial number (2L)
            string strADEffects = comboBoxEdit_AdEffects.SelectedIndex == 10 ? "A" : comboBoxEdit_AdEffects.SelectedIndex.ToString(CultureInfo.InvariantCulture);
            sb.Append(strADEffects);// AD Effects (1L)
            sb.Append(comboBoxEdit_RollSpeed.Text); // 1L
            sb.Append(comboBoxEdit_stayTime.Text); //1L
            sb.Append(1);
            sb.Append(memoEdit_AdContent.Text);

            return sb.ToString();
        }


        private string GetDeleteTaxiAdStrCmd(string aDid)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("FF");
            sb.Append("00");
            sb.Append("Q");
            sb.Append(aDid);//2L
            sb.Append(aDid);//2L
            sb.Append("完");
            return sb.ToString();
        }

        private void UpdateAD() //修改广告
        {

            string strTaxiId = _taxiId;
            string strAdId = comboBoxEdit_AdId.SelectedItem.ToString();
            string strAdContent = memoEdit_AdContent.Text;
            try
            {
                TaxiAdInfo taxiAdUpdate = new TaxiAdInfo
                {

                    TaxiId = int.Parse(strTaxiId),
                    Adid = int.Parse(strAdId),
                    ADContent = strAdContent,
                    ADRollSpeed = comboBoxEdit_RollSpeed.SelectedIndex,
                    ADEffect = comboBoxEdit_AdEffects.SelectedIndex,
                    ADStaytime = comboBoxEdit_stayTime.SelectedIndex
                };
                if (MainForm.PositionService.TaxiAdUpdate(taxiAdUpdate))
                {
                    XtraMessageBox.Show("修改成功！");
                    gridControl1.DataSource = MainForm.PositionService.TaxiAdGetList(
                        "taxiid=" + _taxiId).Tables[0];
                }
                else
                {
                    XtraMessageBox.Show("修改失败！");
                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
            }
        }

        private void AddAD()  //添加广告
        {


            string strTaxiId = _taxiId;
            string strAdId = comboBoxEdit_AdId.SelectedItem.ToString();
            string strAdContent = memoEdit_AdContent.Text;
            try
            {
                TaxiAdInfo taxiAd = new TaxiAdInfo
                {
                    TaxiId = int.Parse(strTaxiId),
                    Adid = int.Parse(strAdId),
                    ADContent = strAdContent,
                    ADRollSpeed = comboBoxEdit_RollSpeed.SelectedIndex,
                    ADEffect = comboBoxEdit_AdEffects.SelectedIndex,
                    ADStaytime = comboBoxEdit_stayTime.SelectedIndex
                };
                if (MainForm.PositionService.TaxiAdAdd(taxiAd))
                {
                    XtraMessageBox.Show("添加成功！");
                    gridControl1.DataSource = MainForm.PositionService.TaxiAdGetList(
                        "taxiid=" + _taxiId).Tables[0];
                }
                else
                {
                    XtraMessageBox.Show("添加失败！");
                }
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
            }
        }

        private bool CheckInput()
        {
            if (comboBoxEdit_AdId.SelectedItem == null)
            {
                XtraMessageBox.Show("请选择广告编号");
                return false;
            }
            string strAdContent = memoEdit_AdContent.Text;
            int intAdlength = strAdContent.Length;
            if (strAdContent.Length > 58)
            {
                XtraMessageBox.Show("广告内容过长（最多为58个汉字或字母）,当前内容为" + intAdlength + "字！");
                return false;
            }
            if (strAdContent.Trim() == "")
            {
                XtraMessageBox.Show("广告内容不能为空！");
                return false;
            }
            return true;

        }

        private void ReceData()
        {
            while (true)
            {
                byte[] receBuffer = new byte[1500];
                byte[] receData;
                #region rece Data
                try
                {
                    int receDataLength = _socket.Receive(receBuffer);
                    Thread.Sleep(1);
                    if (receDataLength == 0 || receDataLength == -1)
                    {
                        break;
                    }
                    receData = new byte[receDataLength];
                    Array.Copy(receBuffer, 0, receData, 0, receData.Length);
                }
                catch (Exception ex)
                {
                    CommonRoutine.HandlingExceptions(ex);
                    break;
                }


                #endregion

                #region
                byte[] realData = OperateAgreement.RestoreReceData(receData);
                if (OperateAgreement.JudgeisCompleteData(realData))
                {

                    ushort messageId = OperateAgreement.GetMessageIdInMessageHead(realData);
                    int packageIndex = OperateAgreement.GetPackageIndexInMessageHead(realData);
                    int packageCount = OperateAgreement.GetPackageCountInMessageHead(realData);
                    int imagedatalength = OperateAgreement.GetMessageLengthInMessageHead(realData);
                    if (packageIndex == 1)
                    {
                        _imageDataBuffer.Clear();
                        _videoDataBuffer.Clear();
                    }

                    byte[] tempbytes = new byte[imagedatalength - 4];
                    Array.Copy(realData, ConstParameters.MBodySatrtIndex + 4, tempbytes, 0, imagedatalength - 4);
                    if (messageId == ConstParameters.CmdTaxiTakeAPhotoReply)
                    {

                        if (!_imageDataBuffer.Keys.Contains(packageIndex))
                        {
                            _imageDataBuffer.Add(packageIndex, tempbytes);
                        }
                        BeginInvoke(new MethodInvoker(delegate()
                        {
                            labelControl_Record.Text = "开始接受数据，请稍等。一共有" + packageCount +
                                "个数据包。当前收到" + _imageDataBuffer.Count + "个。";
                        }));

                        if (_imageDataBuffer.Count == packageCount)
                        {
                            List<byte> templist = new List<byte>();
                            for (int i = 1; i <= packageCount; i++)
                            {
                                templist.AddRange(_imageDataBuffer[i]);
                            }
                            _imageDataBuffer.Clear();
                            try
                            {
                                Bitmap pic = BytesToBitmap(templist.ToArray());
                                if (!Directory.Exists(_imageFloderPath))
                                {
                                    Directory.CreateDirectory(_imageFloderPath);
                                }
                                string imageName = labelControl_TaxiNo.Text + "_" +
                                                   DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                                string fileName = _imageFloderPath + imageName;
                                pic.Save(fileName);
                                BeginInvoke(new MethodInvoker(delegate()
                                                                  {
                                                                      //simpleButton_printscreen.Enabled =
                                                                      //    true;
                                                                      labelControl_Record.Text = "成功获取出租车截图";
                                                                      pictureEdit1.Image = pic;
                                                                  }));

                            }
                            catch (Exception ex)
                            {
                                CommonRoutine.HandlingExceptions(ex);
                                return;
                            }
                        }
                    }
                    else if (messageId == ConstParameters.CmdTaxiTakeAVideoReply)
                    {
                        if (!_videoDataBuffer.Keys.Contains(packageIndex))
                        {
                            _videoDataBuffer.Add(packageIndex, tempbytes);
                        }

                        BeginInvoke(new MethodInvoker(delegate()
                        {
                            labelControl_Record.Text = "开始接受数据，请稍等。一共有" + packageCount +
                                "个数据包。当前收到" + _videoDataBuffer.Count + "个。";
                        }));

                        if (_videoDataBuffer.Count == packageCount)
                        {

                            List<byte> templist = new List<byte>();
                            foreach (int key in _videoDataBuffer.Keys)
                            {
                                templist.AddRange(_videoDataBuffer[key]);
                            }
                            _videoDataBuffer.Clear();
                            MemoryStream m = new MemoryStream(templist.ToArray());
                            if (!Directory.Exists(_videoFloderPath))
                            {
                                Directory.CreateDirectory(_videoFloderPath);
                            }
                            string videoName = labelControl_TaxiNo.Text + "_" +
                                               DateTime.Now.ToString("yyyyMMddHHmmss") + ".amr";
                            string fileName = _videoFloderPath + videoName;
                            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
                            m.WriteTo(fs);
                            m.Close();
                            fs.Close();
                            try
                            {
                                BeginInvoke(new MethodInvoker(delegate()
                                {
                                    // simpleButton_Record.Enabled = true;
                                    labelControl_Record.Text = "接受录音成功。";
                                    axWindowsMediaPlayer2.currentPlaylist.clear();
                                    axWindowsMediaPlayer2.currentPlaylist.appendItem(axWindowsMediaPlayer2.mediaCollection.add(fileName));
                                    axWindowsMediaPlayer2.Ctlcontrols.play();
                                }));
                            }
                            catch (Exception ex)
                            {
                                CommonRoutine.HandlingExceptions(ex);
                                return;
                            }

                        }
                    }
                }

                #endregion

            }
            //this.Invoke(new MethodInvoker(Close));
        }

        private void simpleButton_printscreen_Click(object sender, EventArgs e)
        {
            //  Bitmap sd=new Bitmap();
            _imageDataBuffer.Clear();
            //  simpleButton_printscreen.Enabled = false;
            labelControl_Record.Text = "截图请求发送成功！请稍等。。。。。。。";
            SendData(ConstParameters.CmdTaxiTakeAPhoto, new byte[1]);

        }

        private bool SendData(ushort messageId, byte[] messageBody)
        {
            try
            {
                List<byte> mBytes = new List<byte>();

                mBytes.AddRange(BitConverter.GetBytes(messageId).Reverse());
                mBytes.AddRange(CommonRoutine.BcdStringToBytes(_driverPhone.PadLeft(12, '0')));
                IPAddress localIp = ((IPEndPoint)(_socket.LocalEndPoint)).Address;
                mBytes.AddRange(localIp.GetAddressBytes());
                mBytes.AddRange(messageBody);
                byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdRetweetTaxiDispatchClient, false, false, mBytes.ToArray().Length, new byte[6], new byte[2], 0, 0);
                byte[] sendData = OperateAgreement.PackageSendData(messageHead, mBytes.ToArray());
                _socket.Send(sendData);


                return true;
            }
            catch (Exception ex)
            {
                // simpleButton_Record.Enabled = true;
                // simpleButton_printscreen.Enabled = true;
                labelControl_Record.Text = "请求发送失败。";
                CommonRoutine.HandlingExceptions(ex);
                return false;
            }

        }

        private Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new Bitmap((Image)new Bitmap(stream));
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

        private byte[] BitmapToBytes(Bitmap Bitmap)
        {
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                Bitmap.Save(ms, Bitmap.RawFormat);
                byte[] byteImage = new Byte[ms.Length];
                byteImage = ms.ToArray();
                return byteImage;
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }
        }

        private void simpleButton_Record_Click(object sender, EventArgs e)
        {

            byte[] lBytes = new byte[1];
            byte b = new byte();
            if (!byte.TryParse(textEdit_recrodTime.Text, out b))
            {
                MessageBox.Show("请输入录取时间，必须是整数！");
                return;
            }

            if (b > 30)
            {
                MessageBox.Show("时间必须小于30秒！");
                return;
            }
            lBytes[0] = b;
            _videoDataBuffer.Clear();
            //   simpleButton_Record.Enabled = false;
            labelControl_Record.Text = "录音请求发送成功！请稍等。。。。。。。";
            SendData(ConstParameters.CmdTaxiTakeAVideo, lBytes);
        }


        #region dragWindow

        Point _mouseOff;
        bool _leftFlag;
        private void TaxiCotrolForm_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }

        }

        private void TaxiCotrolForm_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }

        }

        private void TaxiCotrolForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        #endregion

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void TaxiCotrolForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                _socket.Shutdown(SocketShutdown.Both);
                _socket.Close();
                _tReceThread.Abort();
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
            }

        }

    }
}